<template>
    <div>
        <div style="background-color: #f8f8f8;height: 55px" >
            <img v-if="isfocus" @click="gotoback" class="goback" src="../../assets/gobackcustom.png">
            <div v-bind:class="{ 'searchcontxtBg1':isfocus,'searchcontxtBg':!isfocus}">
                <form class="formBg"  @submit.prevent="submit">
                <!--<i class="search-icon"></i>-->
                <!--<yd-icon name="search" color="#e1e1e1" size=".4rem" ></yd-icon>-->
                <input class="searchinput" @focus="checkMobileBlur" type="search" placeholder="搜索" v-model="keyword">
                </form>
            </div>

            <div  v-if="isfocus" class="cancel-text"
               @click="searchClick()">{{cancelText}}</div>
           </div>

        <div v-if="initialAr.length>0">
            <div v-if="isshowhistory">
                <div class="mui-flex" style=" border-bottom: 1px solid #e5e5e5" v-if="searchList.length>0">
                    <div class="cell4">
                        <div class="custom-title">
                            <p>最近搜索</p>
                        </div>
                    </div>
                    <div class="cell" style="background-color: #f8f8f8">
                        <div @click="deleteClick" style="padding-right: 0.3rem">
                            <p  class="delete-title">删除记录</p>
                        </div>
                    </div>
                </div>
                <div v-for="(item,index) in searchList" style="z-index: 1000">
                    <div @click="searchlistClick(index)">
                        <p class="context-title">{{item}}</p>

                    </div>
                </div>
            </div>
        </div>

        <div v-if="isshowcustom">
            <div class="custom-title">
                <p>常用</p>
            </div>
            <div  v-for="(item,index) in commonList" style="z-index: 1000">
                <div  @click="CommonItem(index)">
                    <p class="context-title">{{item.name}}</p>

                </div>
            </div>
        </div>


        <div v-if="jigoulist.length > 0">
            <div v-if="isshowneir">
                <div class="custom-title">
                    <p>按当前距离排序</p>
                </div>
                <yd-infinitescroll :callback="loadList" ref="infinitescrollDemo">
                    <yd-list theme="4" slot="list">
                        <div v-for="(item,index) in jigoulist" @click="selectlistItem(index)">
                            <!--<p v-if="keyword.length>0" v-html="html" class="title">{{item.name}}</p>-->
                            <p  class="titlebg">
                                <span>{{item.fristName}}</span>
                                <span class="actiontitle">{{item.secondName}}</span>
                                <span>{{item.threeName}}</span>

                            </p>

                        </div>
                    </yd-list>

                </yd-infinitescroll>
            </div>

        </div>

        <div v-else style="padding-top: 2rem">
            <div v-if="!isfocus">
                <img src="../../assets/task_none_task_icon.png" class="nolist-image" alt="">
                <p  class="nolist-tite">{{placeName}}</p>
            </div>

        </div>
    </div>

</template>

<script>
    import {showInstSelectForUser,showCommonInstSelect,modifyInstInfo} from "../../pcof/post";
    import {userInfoData,instObject} from '../../globalVariables'
    import util from '../../util.js';

    export default {
        name: "instList",
        data() {
            return {
                initialAr:JSON.parse(localStorage.getItem('insthistorysearch')),
                searchList:[],
                placeName:'没有相关机构信息',
                currentValue: '',
                type:'',
                jigoulist:[],
                commonList:[],
                isshowneir:true,
                isshowcustom:true,
                isfocus:false,
                isshowhistory:false,
                isClickback:false,
                pageNumber: 1,
                cancelText:'搜索',
                pageSize: 20,
                serviceTotalPage: 1,
                selectItem:[],
                keyword:'',
                latitude:0,
                longitude:0,
            };
        },

        watch: {
            keyword: function (newValue, oldValue) {//搜索关键字
                if (newValue === null || newValue === '' || newValue.length <= 0) {
                    if (this.isClickback===true)
                    {
                        this.isClickback=true;
                        this.isshowneir=true;
                        this.isshowcustom=true;
                        this.isfocus=false;
                        this.isshowhistory=false;
                        this.selectItem=[];
                        this.keyword='';
                        this.freshenList();


                    }else
                    {
                        this.keyword = '';
                        this.isfocus=true;
                        this.isshowneir=false;
                        this.isshowhistory=true;
                        this.isClickback=false;
                        this.freshenList();
                    }

                } else {
                    this.isClickback=false;
                    this.isfocus=true;
                    this.isshowhistory=false;
                    this.isshowneir=true;
                    this.keyword = newValue;
                    this.freshenList();
                }
            },
            initialAr: {
                handler(newValue, oldValue) {

                    var newAr = new Array();
                    if (newValue.length > 0) {
                        for (var i = newValue.length - 1; i >= 0; i--) {
                            newAr.push(newValue[i])
                        }
                    }

                    this.searchList = newAr;
                    console.log(this.searchList);

                },
                deep: true
            },
        },
        methods:{
            gotoback()
            {
                this.isClickback=true;
                this.isshowneir=true;
                this.isshowcustom=true;
                this.isfocus=false;
                this.isshowhistory=false;
                this.selectItem=[];
                this.keyword='';

            },
            async checkMobileBlur()
            {
                this.isClickback=false;
                if(this.keyword===''||this.keyword===null)
                {
                    this.isfocus=true;
                    this.isshowhistory=true;
                    this.isshowneir=false;
                    this.isshowcustom=false;
                }else
                {
                    this.isfocus=true;
                    this.isshowhistory=false;
                    this.isshowneir=true;
                    this.isshowcustom=false;

                }


            },
            deleteClick(){

                console.log('删除');
                localStorage.setItem('insthistorysearch', JSON.stringify
            ([]));
                this.isshowhistory=false;
                this.initialAr=JSON.parse(localStorage.getItem('insthistorysearch'));
            },
            searchClick() {

                    this.isfocus=false;
                    this.isshowhistory=false;
                    this.isshowneir=true;
                    this.isshowcustom=false;
                    this.isClickback=false;
                this.freshenList();
                var searAr= new Array();
                searAr=JSON.parse(localStorage.getItem('insthistorysearch'));
                var myArray=[];
                myArray=JSON.parse(localStorage.getItem('insthistorysearch'));

                var  isEqualTo1=false;
                var  isEqualTo2=false;
                if (searAr.length>0)
                {
                    isEqualTo2 = true;
                    //判断搜索内容是否存在，存在的话放到数组最后一位，不存在的话添加。
                    for (var i=0;i<myArray.length;i++)
                    {
                        var name=myArray[i];
                        if (this.keyword ===name)
                        {
                            searAr.splice(i, 1);
                            searAr.push(this.keyword);
                            isEqualTo1 = true;
                            break;
                        }
                    }

                }
                if (!isEqualTo1 || !isEqualTo2) {
                    if (this.keyword===''||this.keyword===null)
                    {

                    }else
                    {
                        searAr.push(this.keyword);
                        console.log(searAr);
                    }

                }

                if(searAr.length > 5)
                {
                    searAr.splice(0,1);

                }
                localStorage.setItem('insthistorysearch',JSON.stringify
                (searAr));
                this.initialAr=JSON.parse(localStorage.getItem('insthistorysearch'));


            },
            searchlistClick(index)//历史数据选中
            {
                 this.keyword=this.searchList[index];
                console.log(this.keyword);
                this.isfocus=false;
                this.isshowhistory=false;
                this.isshowneir=true;
                this.isshowcustom=false;
                this.isClickback=false;
                this.freshenList();

            },

            async submit() {
                //确定搜索
                this.freshenList();

            },
            selectNext()
            {
                console.log(this.selectItem);
                // console.log(this.selectItem);
                if (this.type ==='center') //center （个人中心选择机构）registry （注册选择机构）
                {

                    this.modifyInstInfoFunc();

                }else if (this.type ==='registry')
                {

                }else if (this.type === 'repairEquipMent') {
                    localStorage.setItem(instObject,JSON.stringify(this.selectItem));
                    this.$router.back();
                }else if (this.type === 'repairOrder') {
                    localStorage.setItem(instObject,JSON.stringify(this.selectItem));
                    this.$router.back();
                }
            },
            selectlistItem (index)//列表选择
            {
                this.selectItem=this.jigoulist[index];
                this.selectNext();

            },

           async CommonItem(index)//常用选择
            {
               this.selectItem=this.commonList[index];
                this.selectNext();

            },
            async modifyInstInfoFunc()//修改个人中心机构
            {
                //     mobile,uuid,latitude,longitude,
                var mobile = JSON.parse(localStorage.getItem(userInfoData)).mobile;
                var response = await modifyInstInfo(mobile,this.selectItem.uuid,this.selectItem.latitude,this.selectItem.longitude);
                console.log(response);
                if (response.data.code===200)
                {
                    var dic = new Array();
                    dic = JSON.parse(localStorage.getItem(userInfoData));
                    var newdic = {};
                    for (var key in dic) {
                        if (key === 'bankName') {
                            newdic[key] = this.selectItem.name;

                        } else if (key === 'bankUuid') {
                            newdic[key] = this.selectItem.uuid;

                        }else if (key ==='departmentName')
                        {
                            newdic[key]='';

                        }else if (key ==='departmentUuid') {
                            newdic[key] ='';
                        }else {
                            newdic[key] = dic[key];
                        }
                    }
                    localStorage.removeItem(userInfoData);
                    localStorage.setItem(userInfoData, JSON.stringify
                    (newdic));
                    this.$router.back(-1);

                }else
                {
                    this.$dialog.toast({
                        mes: response.data.msg,
                        timeout: 1500
                    });
                }



            },

            async freshenList()
            {
                // mobile, bankUuid,latitude,longitude,keyword,pageNumber,pageSize

                var mobile = JSON.parse(localStorage.getItem(userInfoData)).mobile;
                var bankUuid=JSON.parse(localStorage.getItem(userInfoData)).partnerUuid;
                this.pageNumber=1;
                this.pageSize=20;
                // mobile,keyword,bankUuid,latitude,longitude,pageNumber,pageSize

                var response = await showInstSelectForUser(mobile,this.keyword,bankUuid,this.latitude,this.longitude,this.pageNumber,this.pageSize);
                this.$dialog.loading.open('加载中...');

                if (response.data.code === 200) {
                    this.$dialog.loading.close();
                    this.jigoulist.splice(0, this.jigoulist.length);//清空数组

                    var list=new Array();
                  list= response.data.data.list;

                    var newAr=new Array();
                    newAr=list;
                    for (var i=0;i<newAr.length;i++)
                    {
                        var dic={};
                        dic=newAr[i];
                        var name=dic.name;
                        var startnum= name.indexOf(this.keyword);//第一次出现的位置
                        var fristName='';
                        var secondName='';
                        var threeName='';
                        if (this.keyword.length===0)
                        {
                            //没有数据关键字
                            fristName=name;
                            secondName='';
                            threeName='';
                        }else
                        {
                            if (startnum===0)//从第一个字开始的
                            {
                                fristName='';
                                secondName=name.substring(0,this.keyword.length);
                                threeName=name.substring(this.keyword.length,name.length);
                            }else
                            {
                                //中间字体
                                fristName=name.substring(0,startnum);
                                secondName=this.keyword;
                                threeName=name.substring(this.keyword.length+startnum,name.length);
                            }
                        }
                        dic['fristName']=fristName;
                        dic['secondName']=secondName;
                        dic['threeName']=threeName;

                        // console.log(dic);
                        // console.log('===='+startnum);
                        // console.log('====111'+fristName);
                        // console.log('====2222'+secondName);
                        // console.log('====333333'+threeName);
                         this.jigoulist.push(dic);

                    }


                    this.serviceTotalPage = response.data.data.totalPage;
                    if (this.keyword.length===0)
                    {
                        this.placeName='没有相关机构信息';

                    }else
                    {
                        this.placeName='未搜寻到相关机构';

                    }
                    if (this.serviceTotalPage > 1) {
                        this.page++;
                    } else {
                        /* 所有数据加载完毕 */
                        this.$refs.infinitescrollDemo.$emit('ydui.infinitescroll.loadedDone');
                    }

                }
                else
                {
                    this.$dialog.loading.close();
                    console.log(response.data.msg);
                    this.$dialog.toast({
                        mes: response.data.msg,
                        timeout: 1500
                    });
                }
            },

            async loadList() {
                // mobile, bankUuid,latitude,longitude,keyword,pageNumber,pageSize

                var mobile = JSON.parse(localStorage.getItem(userInfoData)).mobile;
                var bankUuid=JSON.parse(localStorage.getItem(userInfoData)).partnerUuid;
                var response = await showInstSelectForUser(mobile,this.keyword,bankUuid,this.latitude,this.longitude,
                    this.pageNumber, this.pageSize);
                if (response.data.code === 200) {
                    var _list=new Array();

                    var newAr=new Array();
                    newAr=response.data.data.list;
                    for (var i=0;i<newAr.length;i++) {
                        var dic = {};
                        dic = newAr[i];
                        var name = dic.name;
                        var startnum = name.indexOf(this.keyword);//第一次出现的位置
                        var fristName = '';
                        var secondName = '';
                        var threeName = '';
                        if (this.keyword.length === 0) {
                            //没有数据关键字
                            fristName = name;
                            secondName = '';
                            threeName = '';
                        } else {
                            if (startnum === 0)//从第一个字开始的
                            {
                                fristName = '';
                                secondName = name.substring(0, this.keyword.length);
                                threeName = name.substring(this.keyword.length, name.length);
                            } else {
                                //中间字体
                                fristName = name.substring(0, startnum);
                                secondName = this.keyword;
                                threeName = name.substring(this.keyword.length + startnum, name.length);
                            }
                        }
                        dic['fristName'] = fristName;
                        dic['secondName'] = secondName;
                        dic['threeName'] = threeName;
                        _list.push(dic);
                    }

                        this.jigoulist = [...this.jigoulist, ..._list];


                        if (_list.length < this.pageSize || this.pageNumber === this.serviceTotalPage) {

                       /* 所有数据加载完毕 */
                        this.$refs.infinitescrollDemo.$emit('ydui.infinitescroll.loadedDone');
                        return;
                    }

                    /* 单次请求数据完毕 */
                    this.$refs.infinitescrollDemo.$emit('ydui.infinitescroll.finishLoad');

                    this.pageNumber++;

                } else {

                }
            },
        },
        async created() {
            this.type = this.$route.params.type;//center （个人中心选择机构）registry （注册选择机构）
            console.log(this.type);
            this.initialAr=JSON.parse(localStorage.getItem('insthistorysearch'));
                var newAr=new Array();
            if (this.initialAr.length>0)
            {
                for (var  i=this.initialAr.length-1;i>=0;i--)
                {
                    newAr.push(this.initialAr[i])
                }
            }

            this.searchList=newAr;

            // this.latitude = "30.19827842712402";
            // this.longitude = "120.1998901367188";
            //
            // this.freshenList();

            //
            let that = this;
            wx.ready(function () {
                wx.getLocation({
                    type: 'wgs84', // 默认为wgs84的gps坐标，如果要返回直接给openLocation用的火星坐标，可传入'gcj02'
                    success: function (res) {
                        var latitude = res.latitude; // 纬度，浮点数，范围为90 ~ -90
                        var longitude = res.longitude; // 经度，浮点数，范围为180 ~ -180。
                        that.latitude = latitude;
                        that.longitude = longitude;
                        // that.$dialog.confirm({
                        //     title: '经纬度测试',
                        //     mes: that.latitude+'*****'+that.longitude,
                        //     opts: () => {
                        //         this.$dialog.toast({mes: '你点了确定', timeout: 1000});
                        //     }
                        // });

                        that.freshenList();
                    }
                });
            });

            var mobile = JSON.parse(localStorage.getItem(userInfoData)).mobile;
            this.$dialog.loading.open('加载中...');
            var response = await showCommonInstSelect(mobile,'01');
            if (response.data.code===200){
                this.$dialog.loading.close();
                this.commonList=response.data.data;

            }else
            {
                this.$dialog.loading.close();
                this.$dialog.toast({
                    mes: response.data.msg,
                    timeout: 1500
                });
            }


        },
    }
</script>

<style scoped>
    .custom-title {
        color: #9a9a9a;
        font-size: 0.2rem;
        text-align: left;
        padding-top: 0.25rem;
        padding-left: 0.3rem;
        padding-bottom: 0.15rem;
        background-color: #fafafa;

    }
    .delete-title
    {
        color: #9a9a9a;
        font-size: 0.2rem;
        text-align: center;

        /*width: 1.8rem;*/
        /*right: -5.6rem;*/
        /*top: -0.8rem;*/
        border: 1px solid #e5e5e5;
        padding: 0.1rem 0.2rem 0.1rem 0.2rem;
        border-radius: 4px;
        /*background-color: #fafafa;*/
    }
    .titlebg {
        font-size: 0.25rem;
        color: #858585;
        text-align: left;
        height: 50px;
        padding-top: 20px;
        margin: 0 10px 0 20px;
        border-bottom: 1px solid #e1e1e1;
    }
    .context-title {
        font-size: 0.25rem;
        color: #858585;
        text-align: left;
        height: 50px;
        padding-top: 20px;
        margin: 0 10px 0 20px;
        border-bottom: 1px solid #e1e1e1;
    }
    .actiontitle {
        font-size: 0.25rem;
        color: red;
        text-align: left;
        height: 50px;
        padding-top: 20px;
    }


    .searchcontxtBg {
        position: absolute;
        top: 10px;
        height: 35px;
        left: 0.3rem;
        right: 10px;
        background-color: white;
        border-radius: 4px;
        border: 1px solid #e1e1e1;
    }
    .searchcontxtBg1 {
        position: absolute;
        top: 10px;
        height: 35px;
        left: 0.6rem;
        right: 50px;
        background-color: white;
        border-radius: 4px;
        border: 1px solid #e1e1e1;
    }
    .goback
    {
        margin: 0.28rem 0 0 10px;
        width: 0.2rem;
        height: 0.33rem;
        float: left;
    }
    .formBg {
        padding: 8px 0 10px 0;
    }

    .searchinput {
        height: 100%;
        width: 100%;
        padding-left:10px;
        font-size: 0.25rem;
        border: 0px solid #e1e1e1;
    }

    .cancel-text {
        position: absolute;
        top: 15px;
        height: 35px;
        right: 10px;
        color: #3cc8a8;
        font-size: 0.25rem;

    }
</style>